<script setup>
import { ref,onMounted, nextTick,computed } from 'vue'
import Drawer from '@/components/Drawer.vue'
import AssetsList from '@/components/AssetsList.vue'
import {ElTable, ElTableColumn, ElMessage} from 'element-plus'
import { 

  getLocationTree,
  getBorrowerPersonList,
  getBorrowerList,
  addBorrower,
  getBorrowerDept,
  getBorrowerDetail
} from "@/api/AssetBorrow"

import {Plus, Search, Refresh, View} from '@element-plus/icons-vue'


/***********资产借用表单数据******** */

// 新增资产借用弹框状态
const formVisible = ref(false)

// 资产借用表单实例对象
const formRef = ref(null)

// 资产借用弹框标题
const title = ref('')

// 资产借用表单数据
const borrowForm = ref({
  userId: null,
  assignDate: new Date().toISOString().split('T')[0], // 借用日期，默认今天
  expectedReturn: new Date().toISOString().split('T')[0], // 预计归还日期，默认今天
  deptId: null,
  locationId: null,
  usagePurpose:"",
  assets: []
})

// 资产所在部门列表数据
const assetDept=ref([]);


// 借用后资产位置树形数据
const parentLocations = ref([])

// 获取位置树形结构
const getLocationTreeData = () => {
  getLocationTree().then(res => {
    if (res.code === 200) {
      parentLocations.value = res.data
    }
  })
}


// 提交资产借用表单
const handleSubmit = () => {
  // 添加表单校验

  console.log(borrowForm.value, 789)
  if(borrowForm.value.assets.length<=0) return ElMessage.error('请选择资产')
  formRef.value.validate(async (valid) => {
    if (valid) {
      addBorrower(borrowForm.value).then(res => {
        if (res.code === 200) {
          ElMessage.success(`新增成功`);
          formVisible.value = false;
          // 调用子组件的取消选中方法
          assetsListRef.value?.clearSelection()
          resetForm();
          getBorrowAssetListData(currentPage.value, pageSize.value)
        }
      });
    }
  })
}

// 资源借出列表数据
const borrowerList = ref([])

// 获取借出列表
const getBorrowAssetListData = (pageNum, pageSize) => {
  sessionStorage.setItem("currentPage", JSON.stringify(currentPage.value));
  getBorrowerList({pageNum, pageSize}).then(res => {
    if (res.code === 200) {
      borrowerList.value = res.data.list
      totalPage.value = res.data.total;

    }
  })
}

// 是否为编辑状态
const isEditMode = ref(false)


// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  formRef.value?.resetFields();
  borrowForm.value = {
    userId: null,
    assignDate: new Date().toISOString().split('T')[0], // 借用日期，默认今天
    expectedReturn: new Date().toISOString().split('T')[0], // 预计归还日期，默认今天
    deptId: null,
    locationId: null,
    usagePurpose:"",
    assets: []
  }
}


//点击借出按钮
const addBorrowData = () => {
  //重置表单 修改编辑状态
  resetForm()
  // 获取可借用资产
  // getAssetListData()
  //弹框显示
  formVisible.value = true
  //弹框标题
  title.value = '新增资产借用'
}


// 借用人相关状态
const borrowPersonLoading = ref(false)
const borrowerPersonOptions = ref([])

// 搜索借用人
const searchBorrowerPerson = async (query) => {
  if (query) {
    borrowPersonLoading.value = true
    try {
      const res = await getBorrowerPersonList({ username: query })
      if (res.code === 200) {
        borrowerPersonOptions.value = res.data
      }
    } finally {
      borrowPersonLoading.value = false
    }
  } else {
    borrowerPersonOptions.value = []
  }
}

// 处理借用人选择变化 获取选中的人的详细信息
const handleBorrowerChange = async (personId) => {
  console.log(personId,7878)
  //借用人选择变化后 获取借用的username
  
  if (!personId) return;
  
  // 获取借用人详情
  const res = await getBorrowerDept(personId);
  if (res.code === 200) {
    // 自动填充部门信息
    assetDept.value = res.data.departments;
    // borrowForm.value.deptId = res.data.deptId;
  }
}


// 禁止选中当前日期之前的日期
const disabledExpectedReturnDate = (time) => {
  return time.getTime() < new Date(borrowForm.value.assignDate).getTime()
}

// 定义子组件 ref
const assetsListRef = ref(null)

// 点击取消关闭弹框
const handleCancel = () => {
  formVisible.value = false
  // 调用子组件的取消选中方法
  assetsListRef.value?.clearSelection()
}

// 获取子组件选择借用的资产
const handleAssetSelect = (assetList) =>{
  borrowForm.value.assets = assetList
  console.log(assetList,9999)
}

// 控制 Drawer 显示状态
const drawerVisible = ref(false)

// 点击编号时触发的方法
const handleClickTag = (id) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getBorrowerDetail({id}).then(res => {
    if (res.code === 200) {
      console.log(res,"详情数据")
      nextTick(() => {
        showFormData.value.id = res.data.id
        showFormData.value.createTime = res.data.createTime
        showFormData.value.username = res.data.username
        showFormData.value.deptName = res.data.deptName
        showFormData.value.expectedReturn = res.data.expectedReturn
        showFormData.value.locationName = res.data.locationName
        showFormData.value.usagePurpose = res.data.usagePurpose
        tableData.value = res.data.assets
        console.log(formDataValues.value,7777)
      })
    }
  })
  drawerVisible.value = true
}

// 资产列表搜索框绑定的资产id
const queryForm = ref({
  id: ''
})
// 根据资产id查询借用列表
const handleBorrowSearch = () => {
  if (!queryForm.value.id) {
    ElMessage.warning('请输入资产id');
    return;
  }
  const params = {
    id: queryForm.value.id
  }
  getBorrowerList(params).then(res => {
    if (res.code === 200) {
      borrowerList.value = res.data
    }
  })
}

// 重置资源借用列表数据
const handleBorrowReset = () => {
  queryForm.value.id = ''
  getBorrowAssetListData(currentPage.value, pageSize.value)
}

const showFormData = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  expectedReturn: '',
  locationName: '',
  usagePurpose: '',
  assets:[]
})

const formDataValues = computed( () => [
  {
    label: '借用部门:',
    value: showFormData.value.deptName
  },
  {
    label: '借用人:',
    value: showFormData.value.username
  },
  {
    label: '借后位置:',
    value: showFormData.value.locationName
  },
  {
    label: '备注:',
    value: showFormData.value.usagePurpose
  },
  {
    label: '预归还时间:',
    value: showFormData.value.expectedReturn
  },
  {
    label: '创建时间:',
    value: showFormData.value.createTime
  },
])

// tableData
const tableColumns = ref([
  // { prop: 'assetsId', label: '资产ID' },
  { prop: 'name', label: '资产名称' },  
  { prop: 'categoryName', label: '资产分类' },
  { prop: 'assetCode', label: '资产编码' },
  { prop: 'model', label: '型号规格' },
  // { prop: 'status', label: '状态' },
  // { prop: 'serialNumber', label: '序列号' },
  { prop: 'locationName', label: '位置' }
])

const tableData = ref([])

// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false
}

const rules = {
  userId: [
    { required: true, message: '请选择借用人', trigger: 'change' }
  ],
  locationId: [
    { required: true, message: '请选择位置', trigger: 'change' }
  ],
  assignDate: [
    { required: true, message: '请选择借用日期', trigger: 'change' }
  ],
  expectedReturn: [
    { required: true, message: '请选择预计归还日期', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (new Date(value) < new Date(borrowForm.value.assignDate)) {
          callback(new Error('预计归还日期不能早于借用日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  usagePurpose: [
    { max: 200, message: '备注长度不能超过200个字符', trigger: 'blur' }
  ]
}

/*********** 页面加载时获取数据 *********/
onMounted(() => {
  //获取位置树数据
  getLocationTreeData()

  //获取借出列表数据
  getBorrowAssetListData(currentPage.value, pageSize.value)
})
//分页
const currentPage = ref(1)
const totalPage = ref(0)
const pageSize = ref(10)
currentPage.value = Number(sessionStorage.getItem("currentPage")) || 1;
const handleCurrentChange = (activePage) => {
  sessionStorage.setItem("currentPage", JSON.stringify(activePage));
  currentPage.value = activePage
  console.log(activePage, pageSize.value)
  getBorrowAssetListData(activePage, pageSize.value);
}

</script>

<template>

  <!-- 新增资产借出按钮与按资产名称搜索借用资源列表 -->

  <!-- 搜索框 -->
  <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="margin: 10px 0 0 0;">
    <el-form-item>
      <el-space>
        <el-input v-model="queryForm.id" placeholder="请输入资产ID" clearable style="width: 300px"
                  :prefix-icon="Search">
        <template #append>
          <el-button type="primary" :style="$globalAttribute.primaryButton" :icon="Search" @click="handleBorrowSearch">
            搜索
          </el-button>
        </template>
      </el-input>
        <el-button type="primary" plain :icon="Refresh" @click="handleBorrowReset">
        重置
      </el-button>
        <el-button type="primary" plain :icon="Plus" @click="addBorrowData">
          新增
        </el-button>
      </el-space>
    </el-form-item>
  </el-form>


  <!------------ 新增资产借出弹框表单 ----------->
  <el-dialog v-model="formVisible" @close="handleCancel" :close-on-click-modal="false" :title="title" width="70%">
    <el-form :model="borrowForm" :rules="rules" ref="formRef" label-width="120px" inline>
      <el-form-item label="借用人" prop="userId">
        <el-select
          v-model="borrowForm.userId"
          filterable
          remote
          reserve-keyword
          clearable
          placeholder="请输入借用人姓名"
          :remote-method="searchBorrowerPerson"
          :loading="borrowPersonLoading"
          @change="handleBorrowerChange"
          style="width: 200px"
        >
          <el-option
            v-for="item in borrowerPersonOptions"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        
      </el-form-item>

      <el-form-item label="借用日期" prop="assignDate">
        <el-date-picker
          v-model="borrowForm.assignDate"
          type="date"
          clearable
          placeholder="选择借用日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="预计归还日期" prop="expectedReturn">
        <el-date-picker
          v-model="borrowForm.expectedReturn"
          type="date"
          clearable
          placeholder="选择预计归还日期"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledExpectedReturnDate"
        />
      </el-form-item>

      <el-form-item label="所在部门" prop="deptId" :rules="[{required:true,message:'请选择用户部门'}]">
        <el-tree-select
            v-model="borrowForm.deptId" placeholder="请选择用户部门"
            :data="assetDept"
            node-key="id"
            clearable
            :props="{label:'deptName',children:'children'}"
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>
      </el-form-item>

      <el-form-item label="借用后位置" prop="locationId">
        <el-tree-select
          v-model="borrowForm.locationId" placeholder="请选择上级位置"
          :data="parentLocations"
          node-key="id"
          clearable
          :props="{label:'locationName',children:'children'}"
          check-strictly
          :render-after-expand="false"
          style="width: 200px"
      ></el-tree-select>

      </el-form-item>

      <el-form-item label="备注" class="full-width">
        <el-input 
          v-model="borrowForm.usagePurpose" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入备注内容" 
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 资产列表 -->
      <AssetsList :status="0" ref="assetsListRef" @assetSelect="handleAssetSelect"/>

      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>

  <!-------------- 借用信息列表 --------------->
  <el-table 
    :data="borrowerList"
    height="80%"
    style="margin-top: 10px;cursor:pointer;"
  >
    <!--    <el-table-column prop="id" label="借用id" align="center">-->
    <!--      <template #default="scope">-->
    <!--        <el-tag type="primary" @click="handleClickTag(scope.row.id)">{{ scope.row.id }}</el-tag>-->
    <!--      </template>-->
    <!--    </el-table-column>-->
    <el-table-column prop="dept_name" label="借用部门" align="left" width="150"/>
    <el-table-column prop="username" label="借用人" align="center"/>
    <el-table-column prop="use_status" label="借用状态" align="center">
      <template #default="scope">
        <el-tag type="success" v-if="scope.row.use_status===1">正常使用</el-tag>
        <el-tag type="primary" v-if="scope.row.use_status===2">已退还</el-tag>
        <el-tag type="warning" v-if="scope.row.use_status===4">审批中</el-tag>
        <el-tag type="danger" v-if="scope.row.use_status===5">撤回</el-tag>
        <el-tag type="danger" v-if="scope.row.use_status===6">驳回</el-tag>
        <el-tag type="info" v-if="scope.row.use_status===3">其他</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="location_name" label="借后归属地" align="left"/>
    <el-table-column prop="createTime" label="借用日期" align="center" width="200"/>
    <el-table-column prop="expectedReturn" label="预计归还日期" align="center"/>

<!--    <el-table-column prop="usage_purpose" label="备注" align="center">-->
<!--      <template #default="scope">-->
<!--        <el-tooltip :content="scope.row.usage_purpose" placement="top" :disabled="!scope.row.usage_purpose || scope.row.usage_purpose.length <= 10">-->
<!--          <span class="table-cell-truncate">{{ scope.row.usage_purpose }}</span>-->
<!--        </el-tooltip>-->
<!--      </template>-->
<!--    </el-table-column>-->
    <el-table-column label="操作" align="center" width="150">
      <template #default="scope">
        <el-link type="primary" :icon="View" @click="handleClickTag(scope.row.id)">查看</el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :disabled="disabled"
      :background="background"
      layout=" slot,prev, pager, next"
      :total="totalPage"
      @current-change="handleCurrentChange"
  >
    <el-text key="1">总条数：{{ totalPage }}</el-text>
  </el-pagination>


  <!--------------- 借用详情抽屉 ----------------->
  <Drawer v-model:visible="drawerVisible" :formData="showFormData" :title="'资产借用详情'" :formDataValues="formDataValues" :tableColumns="tableColumns" :tableData="tableData" @close="closeDrawer" />
</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409EFF;
    &::after {
      content: '（可选）';
      font-size: 12px;
      color: #999;
    }
  }
}
.full-width {
  width: 100%;
  
  .el-textarea {
    width: 100%;
  }
}
.table-cell-truncate {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际情况调整 */
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>